package com.changcheng.explorer.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.Thread.State;
import java.math.BigDecimal;
import java.math.MathContext;
import java.util.Properties;
import java.util.Set;
import org.apache.commons.io.FileUtils;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.util.Log;
import com.changcheng.explorer.R;
import com.changcheng.explorer.thread.OnThreadEnd;

enum EDIT_TYPE {
	CUT, COPY
}

public class FSFileUtils {

	private static final String TAG = "FSFileUtils";
	// 剪贴板
	private static EDIT_TYPE editType;
	private static Set<String> selectedFiles;
	private static boolean cancel = false;

	/**
	 * 创建目录
	 * 
	 * @param folderName
	 */
	public static boolean createFolder(String folderName) {
		File file = new File(folderName);
		if (!file.exists()) {
			return file.mkdirs();
		}
		return false;
	};

	/**
	 * 剪切
	 * 
	 * @param path
	 * @throws FileNotFoundException
	 */
	public static void cut(Set<String> pathes) {
		editType = EDIT_TYPE.CUT;
		selectedFiles = pathes;
	}

	/**
	 * 复制
	 * 
	 * @param path
	 * @throws FileNotFoundException
	 */
	public static void copy(Set<String> pathes) throws FileNotFoundException {
		editType = EDIT_TYPE.COPY;
		selectedFiles = pathes;
	}

	/**
	 * 粘贴
	 * 
	 * @throws IOException
	 */
	public static void paste(Context context, final String destPath,
			final OnThreadEnd end) throws IOException {
		if (selectedFiles == null || selectedFiles.size() <= 0)
			return;
		File destDir = new File(destPath);
		if (!destDir.exists() || destDir.isFile())
			throw new FileNotFoundException();
		// 进度对话框
		final ProgressDialog progressDialog = new ProgressDialog(context);
		progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		progressDialog.setMessage("Loading...");
		progressDialog.setCancelable(false);
		progressDialog.setButton(context.getString(R.string.bt_cancel),
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						cancel = true;
						dialog.cancel();
					}
				});
		progressDialog.show();
		progressDialog.setMax(selectedFiles.size());

		// 开始执行操作
		Thread thread = new Thread() {
			public void run() {
				try {
					int progress = 1;
					// 开始操作
					for (String path : selectedFiles) {
						progressDialog.setProgress(progress++);
						progressDialog.setMessage(path);
						// 是否取消操作
						if (cancel) {
							cancel = false;
							return;
						}
						File file = new File(path);
						File destFile = new File(destPath + "/"
								+ file.getName());
						if (editType == EDIT_TYPE.CUT) {// 剪切后的粘贴操作
							if (file.isFile())
								FileUtils.moveFile(file, destFile);
							else
								FileUtils.moveDirectory(file, destFile);
						} else if (editType == EDIT_TYPE.COPY) {// 复制后的粘贴操作
							if (file.isFile())
								FileUtils.copyFile(file, destFile);
							else
								FileUtils.copyDirectory(file, destFile);
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
					Log.e(TAG, e.toString());
				} finally {
					// 清理
					cancel = false;
					selectedFiles.clear();
					progressDialog.dismiss();
				}
			}
		};
		
		thread.start();
		// 线程结束后的动作
		while (thread.getState() != State.TERMINATED) {
			if (end != null)
				end.doSomething();
			else {
				try {
					Thread.sleep(200);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 删除
	 * 
	 * @param path
	 * @throws IOException
	 */
	public static void delete(Context context, final Set<String> pathes,
			OnThreadEnd end) throws IOException {
		if (pathes == null || pathes.size() <= 0)
			return;

		// 进度对话框
		final ProgressDialog progressDialog = new ProgressDialog(context);
		progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		progressDialog.setMessage("Loading...");
		progressDialog.setCancelable(false);
		progressDialog.setButton(context.getString(R.string.bt_cancel),
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						cancel = true;
						dialog.cancel();
					}
				});
		progressDialog.show();
		progressDialog.setMax(selectedFiles.size());

		// 开始执行操作
		Thread thread = new Thread() {
			public void run() {
				try {
					int progress = 1;
					for (String path : pathes) {
						progressDialog.setProgress(progress++);
						progressDialog.setMessage(path);
						if (cancel) {
							cancel = false;
							return;
						}
						File file = new File(path);
						if (!file.exists())
							throw new FileNotFoundException();
						else {
							progressDialog.setMessage(file.getPath());
							if (file.isDirectory())
								FileUtils.deleteDirectory(file);
							else
								file.delete();
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
					Log.e(TAG, e.toString());
				} finally {
					// 清理
					cancel = false;
					selectedFiles.clear();
					progressDialog.dismiss();
				}
			}
		};

		thread.start();
		// 线程结束后的动作
		while (thread.getState() != State.TERMINATED) {
			if (end != null)
				end.doSomething();
			else {
				try {
					Thread.sleep(200);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 取文件尺寸
	 * 
	 * @param path
	 * @return
	 */
	public static String getSize(String path) throws FileNotFoundException {
		File file = new File(path);
		if (!file.exists())
			throw new FileNotFoundException();

		long size;
		if (file.isFile())
			size = file.length();
		else
			size = FileUtils.sizeOfDirectory(file);
		// Math.

		if (size < 1024)
			return size + "B";
		else if (size / 1024 < 1024)
			return round(size / 1024.0) + "KB";
		else if (size / 1024.0 / 1024.0 < 1024)
			return round(size / 1024.0 / 1024.0) + "MB";
		else if (size / 1024.0 / 1024.0 / 1024.0 < 1024)
			return round(size / 1024.0 / 1024.0 / 1024.0) + "GB";
		else
			return "null";
	}

	private static double round(double value) {
		BigDecimal bd = BigDecimal.valueOf(value);
		return bd.round(new MathContext(2)).doubleValue();
	}

	/**
	 * 重命名
	 * 
	 * @param files
	 * @param newName
	 */
	public static void rename(Set<String> files, String newName) {
		if (files == null || files.size() <= 0)
			return;
		else {
			int more = 0;
			for (String item : files) {
				File file = new File(item);
				if (file.exists()) {
					String fileDir = getFileDir(file.getPath());
					String fileSufix = getFileSufix(file.getPath());
					// 批量命名时，在名称前添加序号。
					if (more > 0)
						newName = more + newName;
					// 组装新文件名
					File destFile = new File(fileDir + "/" + newName + "."
							+ fileSufix);

					file.renameTo(destFile);
					++more;
				}
			}
		}
	}

	/**
	 * 取文件后缀名
	 */
	public static String getFileSufix(String path) {
		int length = path.length();
		int dotPosition = path.lastIndexOf(".") + 1;
		return path.substring(dotPosition, length);
	}

	/**
	 * 取文件名
	 */
	public static String getFileName(String path) {
		int length = path.length();
		int namePosition = path.lastIndexOf("/");
		String sufix = getFileSufix(path);
		return path.substring(namePosition, length - sufix.length());
	}

	/**
	 * 取文件目录
	 */
	public static String getFileDir(String path) {
		return path.substring(0, path.lastIndexOf("/"));
	}

	/**
	 * 取文件类型
	 */
	public static String getFileType(String path) {
		Properties fileType = new Properties();
		try {
			fileType.load(FSFileUtils.class.getClassLoader()
					.getResourceAsStream("andoirfiletype.properties"));
		} catch (IOException e) {
			Log.e(TAG, e.toString());
			e.printStackTrace();
		}
		return fileType.getProperty("." + getFileSufix(path));
	}

	/**
	 * 根据文件后缀名，取文件图标
	 */
	public static int getIco(String filePath) {
		String sufix = getFileSufix(filePath);
		if (sufix.equals("aif"))
			return R.raw.aif;
		else if (sufix.equals("chm"))
			return R.raw.chm;
		else if (sufix.equals("dat"))
			return R.raw.dat;
		else if (sufix.equals("doc"))
			return R.raw.doc;
		else if (sufix.equals("dot"))
			return R.raw.dot;
		else if (sufix.equals("dvd"))
			return R.raw.dvd;
		else if (sufix.equals("inf"))
			return R.raw.inf;
		else if (sufix.equals("ini"))
			return R.raw.ini;
		else if (sufix.equals("ip"))
			return R.raw.ip;
		else if (sufix.equals("max"))
			return R.raw.max;
		else if (sufix.equals("mp3"))
			return R.raw.mp3;
		else if (sufix.equals("pdf"))
			return R.raw.pdf;
		return R.drawable.file;
	}
}
